package controlebens.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import controlebens.been.UsuarioInfo;
import controlebens.dao.Conexao;
import controlebens.dao.LoginDAO;
import controlebens.interceptor.AcessoLiberado;
import controlebens.model.Login;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;

/**
 * @author Jefferson Stachelski
 */
@Resource
public class LoginController{
    private final Result result;
    private final Validator validator;
    private final UsuarioInfo usuarioInfo;
    private final LoginDAO loginDAO;
    private final Connection conexao;
	private final EntityManager entityManager;
    
    public LoginController(UsuarioInfo usuarioInfo, Result result, Validator validator, EntityManager entityManager) throws Exception{
        //this.funcionarioDAO = funcionarioDAO;
        this.usuarioInfo = usuarioInfo;
        this.result = result;
        this.validator = validator;
        this.conexao = Conexao.getConexao();
        this.loginDAO = new LoginDAO(conexao);
		this.entityManager = entityManager;
    }
    
    public void fecharConexao() {
        if(this.conexao != null) try {
            this.conexao.close();
        } catch (SQLException e) {
            System.out.println("Erro: " + e.getMessage());
        }
    }
    
    @AcessoLiberado
    @Path("/login") @Get
    public void login(){
        /*if(validator != null || validator.getErrors().size() <= 0)
            validator.getErrors().clear();*/
    }
    
    @AcessoLiberado
    @Path("/login") @Post
    public void efetuarLogin(Login login){
        //System.out.println("Usuario: "+login.getUsuario()+"\nSenha: "+login.getSenha());
        try{
            if(this.loginDAO.validarLogin(login)){
                usuarioInfo.login(this.loginDAO.getFuncionario(login));
                this.result.redirectTo(HomeController.class).home();
            }
            else{
                validator.add(new ValidationMessage("Login e/ou senha inválidos", "usuario.login"));
                validator.onErrorUsePageOf(LoginController.class).login();
                //this.result.include("validacao", false);
                this.result.redirectTo(LoginController.class).login();
            }
        }
        catch(Exception e){
            this.result.include("erro", e.getMessage());
            this.result.redirectTo(LoginController.class).login();
        }
        finally{
            this.fecharConexao();
        }
    }    
}
